<template>
	<view class="container">
		<view class="login-head-box">
			<text class="title">账户登录</text>
		</view>
		<view class="login-head-tab">
			<text @click="loginMethod=0" class="text-box line" :class="{active:loginMethod===0}">密码登录</text>
			<text @click="loginMethod=1" class="text-box" :class="{active:loginMethod===1}">手机登录</text>
		</view>
		
		<!--用户名密码登录.开始-->
		<view v-if="loginMethod===0" class="login-form-list">
			<view class="item-box">
				<input type="text" v-model="loginForm.username" placeholder="请输入用户名" class="input" />
			</view>
			<view class="item-box">
				<input password v-model="loginForm.password" placeholder="请输入密码" class="input" />
			</view>
			<view class="item-box">
				<view class="left">
					<input type="text" v-model="loginForm.codeValue" placeholder="请输入验证码" class="input" />
				</view>
				<view @click="toggleCode" class="code">
					<image mode="widthFix" :src="imgSrc"></image>
				</view>
			</view>
			<view class="btn-box">
				<button @click="submitForm" class="btn submit">登录</button>
				<navigator url="reset/password" class="btn">忘记密码?</navigator>
			</view>
		</view>
		<!--用户名密码登录.结束-->
		
		<!--手机验证码登录.开始-->
		<view v-if="loginMethod===1" class="login-form-list">
			<view class="item-box">
				<input type="text" v-model="phoneForm.phone" placeholder="请输入手机号码" class="input" />
			</view>
			<view class="item-box">
				<view class="left">
					<input type="text" v-model="phoneForm.codeValue" placeholder="请输入手机验证码" class="input" />
				</view>
				<view class="right">
					<text v-if="timer>0" class="send gray">重新获取({{timer}}s)</text>
					<text v-else @click="sendCode" class="send">获取验证码</text>
				</view>
			</view>
			<view class="btn-box">
				<button @click="submitPhoneForm" class="btn submit">登录</button>
			</view>
		</view>
		<!--手机验证码登录.结束-->
		
		<!--第三方登录.开始-->
		<view v-if="oauthList.length>0" class="group-box">
			<view class="stitle">
				<text class="title">快捷登录</text>
			</view>
			<view class="oauth-box">
				<view v-for="(item,index) in oauthList" :key="index" class="list-box">
					<view v-if="item.provider=='wechat'&&item.type=='mp'" class="btn-box">
						<button class="btn" open-type="getPhoneNumber" @getphonenumber="phoneNumberLogin">
							<image mode="widthFix" :src="$api.loadFile(item.imgUrl)"></image>
							{{item.title}}
						</button>
					</view>
					<view v-else @click="submitOAuth(item.provider,item.type)" class="btn-box">
						<view class="icon">
							<image mode="widthFix" :src="$api.loadFile(item.imgUrl)"></image>
						</view>
						<text class="text">{{item.title}}</text>
					</view>
				</view>
			</view>
		</view>
		<!--第三方登录.结束-->
		
		<view class="login-foot-box">
			还没有账号？<navigator url="register" class="link">马上注册</navigator>
		</view>
	</view>
</template>

<script>
	import {mapMutations} from 'vuex';
	
	export default {
		data() {
			return {
				timer: 0, //计时器
				loginMethod: 0, //登录方式0用户名密码1手机验证码
				imgSrc: null, //验证码路径
				oauthList: [], //授权平台列表
				mpJsCode: '', //小程序JSCode，由于要在页面加载时获取
				loginForm: {
					username: 'test',
					password: 'abc123123',
					codeKey: null,
					codeValue: null
				},
				phoneForm: {
					phone: null,
					codeKey: null,
					codeValue: null
				},
			}
		},
		methods: {
			//初始化
			initData() {
				let _this = this;
				//加载验证码
				_this.toggleCode();
				
				//根据环境加载授权列表
				let sendUrl=`/client/oauth/view/0`;
				
				//#ifdef H5
				sendUrl+=`?types=h5`;
				//#endif
				
				//#ifdef MP
				sendUrl+=`?types=mp`;
				//#endif
				
				//#ifdef APP-PLUS
				sendUrl+=`?types=app`;
				//#endif
				
				_this.$api.request({
					url: sendUrl,
					method: "get",
				}).then((res) => {
					_this.oauthList = res.data;
				})
			},
			//提交密码登录表单
			submitForm(){
				let _this = this;
				let model = _this.loginForm;
				if(!model.username){
					this.$api.msg('请输入用户名');
					return;
				}
				if(!model.password){
					this.$api.msg('请输入登录密码');
					return;
				}
				if(!model.codeValue){
					this.$api.msg('请输入验证码');
					return;
				}
				_this.$api.request({
					url: "/auth/login",
					method: "post",
					loading: true,
					data: model
				}).then((res) => {
					let token = { 'accessToken' : res.data.accessToken, 'refreshToken' : res.data.refreshToken };
					uni.setStorageSync('qymall_client_token', token);
					//跳转会员中心
					uni.switchTab({
					    url: 'index'
					});
				})
			},
			//切换图形验证码
			toggleCode() {
				let _this = this;
				_this.$api.request({
					url: "/verifycode",
				}).then((res) => {
					_this.loginForm.codeKey = res.data.key
					_this.imgSrc = res.data.data
				})
			},
			//提交手机登录表单
			submitPhoneForm(){
				let _this = this;
				let model = _this.phoneForm;
				if(!/(^1[3|4|5|7|8][0-9]{9}$)/.test(model.phone)){
					this.$api.msg('请输入正确的手机号码');
					return;
				}
				if(!model.codeKey){
					this.$api.msg('请先获取手机验证码');
					return;
				}
				if(!model.codeValue){
					this.$api.msg('请输入手机验证码');
					return;
				}
				_this.$api.request({
					url: "/auth/login/phone",
					method: "post",
					loading: true,
					data: model
				}).then((res) => {
					let token = { 'accessToken' : res.data.accessToken, 'refreshToken' : res.data.refreshToken };
					uni.setStorageSync('qymall_client_token', token);
					//跳转会员中心
					uni.switchTab({
					    url: 'index'
					});
				})
			},
			//获取手机验证码
			sendCode(){
				let _this = this;
				if(!/(^1[3|4|5|7|8][0-9]{9}$)/.test(_this.phoneForm.phone)){
					this.$api.msg('请输入正确的手机号码');
					return;
				}
				//发送短信
				_this.$api.request({
					url: `/verifycode/mobile/${_this.phoneForm.phone}`,
					loading: true,
				}).then((res) => {
					_this.timer = 120; //设置120秒
					_this.countDown();//开始倒计时
					_this.phoneForm.codeKey = res.data.codeKey;
				})
			},
			//获取验证码计时器
			countDown(){
				let _this = this;
				if(_this.timer>0){
					_this.timer--;
					setTimeout(function() {
						_this.countDown();
					},1000)
				}
			},
			//提交授权登录
			submitOAuth(provider, type){
				let _this=this;
				//H5
				if(type=="web" || type=="h5"){
					_this.redirectUrl(provider, type);
				}
				//小程序和APP
				else{
					_this.jsCodeOAuth(provider, type);
				}
			},
			//H5获取授权跳转URL
			redirectUrl(provider, type){
				let _this = this;
				let href = `${window.location.href}?provider=${provider}`;
				let uri = encodeURIComponent(href);
				//调用获取授权接口
				_this.$api.request({
					url: `/oauth/redirect?siteId=${_this.$site}&provider=${provider}&type=${type}&redirectUri=${uri}`,
				}).then(res=>{
					window.location.href = res.data;
				});
			},
			//H5授权登录
			h5OAuth(provider,code){
				let _this = this;
				let href = window.location.href;
				href = href.substring(0, href.indexOf('?'));
				href = `${href}?provider=${provider}`;
				let uri = encodeURIComponent(href);
				//调用获取授权接口
				_this.$api.request({
					url: `/oauth/login`,
					method: "post",
					loading: true,
					data: {
						provider: provider,
						code: code,
						type: "h5",
						redirectUri: uri
					}
				}).then(res=>{
					let token = { 'accessToken' : res.data.accessToken, 'refreshToken' : res.data.refreshToken };
					uni.setStorageSync('qymall_client_token', token);
					//跳转会员中心
					uni.switchTab({
					    url: 'index'
					});
				});
			},
			//小程序和APP登录
			jsCodeOAuth(provider, type){
				let _this = this;
				let uniProvider=provider;
				if(provider=="wechat") uniProvider="weixin";
				//微信小程序废除了旧接口，所以另外处理
				//获取用户信息
				uni.getUserProfile({
					desc: '授权登录',
					success(infoRes) {
						//console.log(infoRes.userInfo.nickName);
						uni.login({
							provider: uniProvider,
							onlyAuthorize: true,
							success(loginRes) {
								//console.log(loginRes.code);
								//调用获取授权接口
								_this.jsCodeLogin(provider,type,loginRes.code,infoRes.userInfo.nickName,infoRes.userInfo.avatarUrl);
							}
						});
					}
				});
			},
			//调用获取授权接口
			jsCodeLogin(provider,type,code,nickName,avatarUrl){
				let _this=this;
				_this.$api.request({
					url: `/oauth/login`,
					method: "post",
					loading: true,
					data: {
						siteId: _this.$site,
						provider: provider,
						type: type,
						code: code,
						realName: nickName,
						avatar: avatarUrl
					}
				}).then(res=>{
					let token = { 'accessToken' : res.data.accessToken, 'refreshToken' : res.data.refreshToken };
					uni.setStorageSync('qymall_client_token', token);
					//跳转会员中心
					uni.switchTab({
					    url: 'index'
					});
				});
			},
			//微信小程序手机授权接口
			phoneNumberLogin(e) {
				let _this = this;
				if(e.detail.errMsg=='getPhoneNumber:ok') {
					_this.$api.request({
						url: `/oauth/login`,
						method: "post",
						loading: true,
						data: {
							provider: 'wechat',
							type: 'mp',
							isMobile: 1,
							code: _this.mpJsCode,
							encryptedData: e.detail.encryptedData,
							encryptIv: e.detail.iv
						}
					}).then(res=>{
						let token = { 'accessToken' : res.data.accessToken, 'refreshToken' : res.data.refreshToken };
						uni.setStorageSync('qymall_client_token', token);
						//跳转会员中心
						uni.switchTab({
						    url: 'index'
						});
					});
				}
			},
			//提取CODE
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null;
			},
		},
		//页面加载完成
		onLoad(options){
			let _this = this;
			
			//#ifdef H5
			//如果是授权回调则直接登录
			let code = this.getUrlCode("code");
			if(options.provider&&code){
				this.h5OAuth(options.provider,code);
			}
			//#endif
			
			//初始化数据
			this.initData();
		},
		//页面初始化
		onShow(options){
			let _this = this;
			
			//#ifdef MP-WEIXIN
			//微信小程序需要提前获取JSCode
			uni.login({
				provider: 'weixin',
				onlyAuthorize: true,
				success(loginRes) {
					_this.mpJsCode = loginRes.code;
				}
			});
			//#endif
		}
	}
</script>

<style lang="scss">
	page{
		background: #fff;
	}
	.oauth-box{
		display: flex;
		justify-content: center;
		flex-flow: row wrap;
		.list-box{
			display: flex;
			flex-flow: row wrap;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin: 24rpx 24rpx 0;
			.btn-box{
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				.icon{
					position: relative;
					margin-bottom: 12rpx;
					padding: 10rpx;
					width: 64rpx;
					height: 64rpx;
					border: 2rpx solid #f0f0f0;
					border-radius: 50%;
					overflow: hidden;
					image{
						width: 100%;
					}
				}
				.text{
					color: #666;
					font-size: 24rpx;
				}
				.btn{
					display: flex;
					align-items: center;
					justify-content: center;
					margin-bottom: 24rpx;
					padding: 12rpx 24rpx;
					color: #666;
					font-size: 26rpx;
					line-height: 84rpx;
					image{
						margin-right: 10rpx;
						width: 64rpx;
						height: 64rpx;
					}
				}
			}
		}
	}
</style>
